package servlets;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.MockUserRepo;
import model.User;
import model.UserRepo;


public class LoginServlet extends HttpServlet {
  private static final long serialVersionUID = 1L;
  private UserRepo user_repo = MockUserRepo.getInstance();

  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    RequestDispatcher dispacher;

    if(req.getSession() != null){
      //System.out.println("redirijo al indexservlet");
      if(req.getSession().getAttribute("loggeduser")!=null){
        //System.out.println("el usuario logueado existe en el servlet");
        req.getSession().setAttribute("loggeduser", null);
      }
    }
    
    dispacher = getServletContext().getRequestDispatcher("/IndexServlet");
    dispacher.forward(req, resp);
  }

  @Override
  protected void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    RequestDispatcher dispacher;
    String name = (String)req.getParameter("name");
    String pass = (String)req.getParameter("pass");
    User u=null;
    Boolean status=true;

    try{
      u = user_repo.getUser(name, pass);
    }catch(RuntimeException e){
      status = false;
      req.setAttribute("error", e.getMessage());
    }

    if(status){
      req.setAttribute("user", u);
    }

    req.setAttribute("status", status);
    dispacher = getServletContext().getRequestDispatcher("/index.jsp");
    dispacher.forward(req, resp);
  }
  
  
}
